#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# @Project : RAG-demo
# @File    : logger_setup_util.py
# @IDE     : PyCharm
# @Author  :ZH
# @Time    : 2025/6/27 17:45
import logging
import os
from logging.handlers import RotatingFileHandler


class LoggerSetup:
    def __init__(self, name="my_project", level=logging.INFO, log_file=None):
        """
        初始化日志器
        :param name: logger 名称（通常为模块名 __name__）
        :param level: 日志级别
        :param log_file: 日志文件路径（如果需要写入文件）
        """
        self.logger = logging.getLogger(name)
        self.logger.setLevel(level)

        if not self.logger.handlers:
            # 防止重复添加 handler（在多个模块导入时避免重复日志）

            # 控制台输出
            console_handler = logging.StreamHandler()
            console_formatter = logging.Formatter(
                fmt='%(asctime)s [%(levelname)s] %(name)s:%(lineno)d - %(message)s',
                datefmt='%Y-%m-%d %H:%M:%S'
            )
            console_handler.setFormatter(console_formatter)
            self.logger.addHandler(console_handler)

            # 文件输出（可选）
            if log_file:
                os.makedirs(os.path.dirname(log_file), exist_ok=True)
                file_handler = RotatingFileHandler(log_file, maxBytes=5*1024*1024, backupCount=5)
                file_formatter = logging.Formatter(
                    fmt='%(asctime)s [%(levelname)s] %(name)s:%(lineno)d - %(message)s',
                    datefmt='%Y-%m-%d %H:%M:%S'
                )
                file_handler.setFormatter(file_formatter)
                self.logger.addHandler(file_handler)

    def get_logger(self):
        return self.logger
